package com.mall.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mall.common.model.GlobalResponse;
import com.mall.dao.ProductMapper;
import com.mall.enums.GlobalResponseEnum;
import com.mall.pojo.Product;
import com.mall.service.ICategoryService;
import com.mall.service.IProductService;
import com.mall.vo.ProductDetailVO;
import com.mall.vo.ProductVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static com.mall.enums.ProductStatusEnum.DELETE;
import static com.mall.enums.ProductStatusEnum.OFF_SALE;

@Service
@Slf4j
public class ProductServiceImpl implements IProductService {
    @Autowired
    private ICategoryService categoryService;

    @Autowired
    private ProductMapper productMapper;

    @Override
    public GlobalResponse<PageInfo<ProductVO>> list(Integer categoryId, Integer pageNum, Integer pageSize) {
        Set<Integer> categoryIdSet = new HashSet<>();
        if (categoryId!=null){
            categoryService.findSubCategoryId(categoryId,categoryIdSet);
            categoryIdSet.add(categoryId);
        }
        PageHelper.startPage(pageNum,pageSize);
        List<Product> productList = productMapper.selectByCategoryIdSet(categoryIdSet);
        List<ProductVO> productVOList = productList.stream()
                .map(product -> {
                    ProductVO productVO = new ProductVO();
                    BeanUtils.copyProperties(product, productVO);
                    return productVO;
                })
                .collect(Collectors.toList());

        PageInfo<ProductVO> pageInfo = new PageInfo<ProductVO>(productVOList);
        return GlobalResponse.successByData(pageInfo);
    }

    @Override
    public GlobalResponse<ProductDetailVO> detail(Integer productId) {
        Product product = productMapper.selectByPrimaryKey(productId);

        if (product.getStatus().equals(OFF_SALE.getCode())
                ||product.getStatus().equals(DELETE.getCode())){
            return GlobalResponse.error(GlobalResponseEnum.PRODUCT_OFF_SALE_OR_DELETE);
        }

        ProductDetailVO productDetailVO = new ProductDetailVO();
        BeanUtils.copyProperties(product,productDetailVO);
        /*库存敏感数据*/
        productDetailVO.setStock(product.getStock()>100?100:product.getStock());

        return GlobalResponse.successByData(productDetailVO);
    }
}
